package com.cpj.bsyyzx.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cpj.bsyyzx.entity.Permission;
import com.cpj.bsyyzx.service.IPermissionService;
import com.cpj.bsyyzx.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 五个臭皮匠
 * @since 2021-05-09
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    IPermissionService permissionService;
    @RequestMapping("/list")    
    CommonResult list(Permission permission,Page page) {
        page.setSize(5);
        return CommonResult.success(permissionService.list(permission,page));
    }
    @PostMapping("/add")
    CommonResult add(Permission permission) {

        if(permissionService.add(permission))
            return CommonResult.success("ok");
        else
            return CommonResult.failed("权限名已经存在");
    }
    @RequestMapping("/getById")
    CommonResult getById(Integer id) {
        return CommonResult.success(permissionService.getById(id));
    }
    @RequestMapping("/update")
    CommonResult update(Permission permission) {
        return CommonResult.success(permissionService.updateById(permission));
    }
    @RequestMapping("/del")
    CommonResult del(Permission permission) {
        permission.setActive(0);
        return CommonResult.success(permissionService.updateById(permission));
    }

    @RequestMapping("/back")
    CommonResult back(Permission permission) {
        permission.setActive(1);
        return CommonResult.success(permissionService.updateById(permission));
    }

    @RequestMapping("userPermissionList")
    CommonResult userPermissionList(HttpServletRequest request){
        String method = request.getMethod();
        if(method.toLowerCase().equals("option")){
            CommonResult.success(null);
        }
        String token = request.getHeader("token");
        JWTVerifier verifier= JWT.require(Algorithm.HMAC256("loginUser")).build();
        DecodedJWT jwt =verifier.verify(token);
        Integer accId = jwt.getClaim("accId").asInt();
        return CommonResult.success(permissionService.userPermissionList(accId));
    }
}
